package bat.iog.hytool.nio.demo1;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class ClientReadThread implements Runnable {

    private static volatile boolean connected = true;
    /**
     * 消息缓存区
     */
    private static ByteBuffer readBuf = ByteBuffer.allocate(1024);

    private int count = 0;

    private Selector selector;

    public ClientReadThread(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        while (connected) {
            try {
                //获取选择器
                selector.select();
                //获取选择器的已选择键集
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectedKeys.iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    //处理完当前的key需要删除，防止重复处理
                    it.remove();
                    if (key.isConnectable()) {
                        System.out.println("客户端【读写线程】尝试连接服务端.....");
                        SocketChannel channel = (SocketChannel) key.channel();
                        channel.configureBlocking(false);
                        //完成连接
//                        channel.register(selector,SelectionKey.OP_WRITE);
                        channel.finishConnect();
                        //监听读事件 循环键集 下次会在读的线程等待
                        key.interestOps(SelectionKey.OP_READ);
                        System.out.println("【读写线程】连接成功");
                    }
                    //数据是否可读
                    if (key.isReadable()) {
                        getMessage(key);
                    }
                    //检查套接字是否已经准备写数据
                    if (key.isWritable()) {
                        writeMessage(key);
//                        sendMessage(key);
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送数据
     *
     * @param key
     * @throws IOException
     */
    private void sendMessage(SelectionKey key) {
        //FIXME 这种就是比较普通的 模拟客户端与服务器端长连接发送消息一直监听写事件 一直在发送数据
        SocketChannel channel = (SocketChannel) key.channel();
        try {
            channel.configureBlocking(false);
            String requestLine = "【客户端】发送消息" + count;
            channel.write(ByteBuffer.wrap(requestLine.getBytes()));
            key.interestOps(SelectionKey.OP_READ);
            count++;
            if (count > 10) {
                channel.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取数据
     *
     * @param key
     * @throws IOException
     */
    private void getMessage(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        channel.configureBlocking(false);
        //清空缓存数据
        readBuf.clear();
        //读取数据
        int count = channel.read(readBuf);
        byte[] bytes = new byte[count];
        //弹出数据
        readBuf.flip();
        readBuf.get(bytes);
        String message = new String(bytes, 0, count);
        System.out.println("服务端响应:~~~~~~~~~");
        System.out.println(message);
        //监控事件 当是connect消息的时候继续监听读事件
//        key.interestOps(SelectionKey.OP_WRITE);
        if(!message.contains("connect")){
            //FIXME 如果我监听的是 聊天消息事件，我就需要监听我的写消息事件 给服务端回消息
            key.interestOps(SelectionKey.OP_WRITE);
        }else{
            //FIXME  当我接收的是服务端发来的消息connect内容的 我继续监听我的读事件，这样客户端再次发送消息我可以继续收到
            key.interestOps(SelectionKey.OP_READ);
        }
    }

    /**
     * 键盘输入模拟聊天发送消息
     * @param key
     * @throws IOException
     */
    private void writeMessage(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();
        channel.configureBlocking(false);
        //键盘输入
        Scanner scanner = new Scanner(System.in);
        StringBuffer stringBuffer =new StringBuffer();
        while (scanner.hasNextLine()){
            String message = scanner.nextLine();
            //FIXME 这里我做了一个操作，如果我连续键盘输入多行信息，只有当一行只输入s时候推出循环，发送消息并且监听我的读消息事件
            if(message.equals("s")){
                break;
            }else{
                stringBuffer.append(message).append("\n");
            }
        }
        channel.write(ByteBuffer.wrap(stringBuffer.toString().getBytes()));
        //监控读事件
        key.interestOps(SelectionKey.OP_READ);
    }
}
